#include "Log.hpp"
#include "util.hpp"

#include <pthread.h>

int main(int argc, char *argv[])
{
  if(argc != 3)
  {
    logMessage(FATAL,"\n\t ./client ip port");
    exit(1);
  }
  std::string ip = argv[1];
  uint16_t port = atoi(argv[2]);

  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if(sockfd < 0)
  {
    logMessage(FATAL,"sock fail");
    exit(SOCKET_ERR);
  }
  //填写远端主机信息
  struct sockaddr_in server;
  bzero(&server,sizeof(server));

  server.sin_family = AF_INET;
  server.sin_port = htons(port);
  inet_aton(ip.c_str(), &server.sin_addr);
  //开始connect
  if(connect(sockfd, (const struct sockaddr*)&server,sizeof(server)) != 0)
  {
    logMessage(FATAL,"connect fail");
    exit(CONN_ERR);
  }
  logMessage(DEBUG,"connect success");

  bool flag = true;
  while(flag)
  {
    char message[1024];
    std::cout << "Please Enter(just number and -1 is quit)# ";
    std::cin >> message;
    if(message == NULL)
      flag = false;
    ssize_t s = write(sockfd, &message, sizeof(message));
    if(s > 0)
    {
      std::string serMessage;
      serMessage.resize(1024);

      ssize_t s = read(sockfd, (char *)serMessage.c_str(), serMessage.size());
      if(s <= 0) break;

      serMessage[s] = 0;
      std::cout << "sever echo: " << serMessage << std::endl;
    }
    if(s < 0)
    {
      std::cout << "write fail" << std::endl;
      exit(1);
    }
  }
  close(sockfd);
  return 0;
}
